// 作者:于大明

//------------------------------mock数据引入---------------------------
import messageMock from './message_mock.js';

//------------------------------mixins引入---------------------------
import messageMixins from './message_mixins.js';


//------------------------------组件引入-------------------------------


//-------------------------Service引入----------------------------------
import CY17 from '@/service/CY/CY17AppService.js';

//--------------------------核心规范-------------------------------------
//1 能不能在页面单行代码实现
//2 能不能不用data methods去实现这个功能(有返回值不用传参数的用compute,有返回值有传参的那么使用filters实现)
//3 以最少的代码实现功能(需要封装除外)
//4 相同代码一定更要封装 区分职责关系 
//5 新增功能时尽量不改之前的文件 以新增组件进行处理


export default {
	// 组件放在data前面
	components: {

	},
	mixins: [messageMixins],
	// 职责: 程序中需要进行set的数据 就是页面交互需要改的数据 比如点击checkbox 需要设置true false 和存放ajax的输入输出 (尽量少去定义data里面的属性 多用computed或者组件进行处理) 
	//1 能不能在页面单行代码实现
	//2 能不能不用data methods去实现这个功能
	data() { // data的定义把每一块都分开
		return {
			unreadTotal: 0,
			conversations: [],

			actionPopup: {
				conversation: null,
				visible: false
			},
			currentUser: null
		};
	},
	// 页面加载事件
	onLoad(options) {},
	// 页面显示事件
	onShow() {
		let currentUser = this.$myIm.getCurrentUser();
		if (!currentUser) {
			uni.navigateTo({
				url: '../login/login'
			})
			return;
		}
		this.currentUser = currentUser;

		if (this.goEasy.getConnectionStatus() === 'disconnected') {
			this.connectGoEasy(); //连接goeasy
			this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
		}
		this.listenConversationUpdate(); //监听会话列表变化
		this.loadConversations(); //加载会话列表
		this.renderConversations(this.$cw.ImMessages);
	},
	// 页面触底事件
	onReachBottom() {},
	// 页面下拉事件
	onPullDownRefresh() {},
	// 职责:页面事件进行交互
	methods: {
		connectGoEasy() {
			uni.showLoading();
			this.goEasy.connect({
				id: this.currentUser.uuid,
				data: {
					name: this.currentUser.name,
					avatar: this.currentUser.avatar
				},
				onSuccess: () => {
					console.log('GoEasy connect successfully.')
				},
				onFailed: (error) => {
					console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
				},
				onProgress: (attempts) => {
					console.log('GoEasy is connecting', attempts);
				}
			});
		},

		// 加载最新的会话列表
		loadConversations() {
			this.goEasy.im.latestConversations({
				onSuccess: (result) => {
					let content = result.content;
					this.renderConversations(content);
					uni.hideLoading();
				},
				onFailed: (error) => {
					uni.hideLoading();
					console.log('获取最新会话列表失败, error:', error);
				}
			});
		},
		listenConversationUpdate() {
			// 监听会话列表变化
			this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
				this.renderConversations(content);
			});
		},
		subscribeGroup() {
			let groups = this.$myIm.findGroups(this.currentUser);
			let groupIds = groups.map(item => item.uuid);
			this.goEasy.im.subscribeGroup({
				groupIds: groupIds,
				onSuccess: function() {
					console.log('订阅群消息成功');
				},
				onFailed: function(error) {
					console.log('订阅群消息失败:', error);
				}
			});
		},
		topConversation() { //会话置顶
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			let actionPopup = this.actionPopup;
			actionPopup.visible = false;

			let conversation = actionPopup.conversation;
			let failedDescription = conversation.top ? '取消置顶失败' : '置顶失败';

			if (conversation.type === this.GoEasy.IM_SCENE.PRIVATE) {
				this.goEasy.im.topPrivateConversation({
					userId: conversation.userId,
					top: !conversation.top,
					onSuccess: function() {
						uni.hideLoading();
					},
					onFailed: function(error) {
						uni.hideLoading();
						uni.showToast({
							title: failedDescription,
							icon: 'none'
						});
						console.log(error);
					}
				});
			} else {
				this.goEasy.im.topGroupConversation({
					groupId: conversation.groupId,
					top: !conversation.top,
					onSuccess: function() {
						uni.hideLoading();
					},
					onFailed: function(error) {
						uni.hideLoading();
						uni.showToast({
							title: failedDescription,
							icon: 'none'
						});
						console.log(error);
					}
				});
			}
		},
		deleteConversation() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			let failedDescription = '删除失败';
			let conversation = this.actionPopup.conversation;
			this.actionPopup.visible = false;

			if (conversation.type === this.GoEasy.IM_SCENE.PRIVATE) {
				this.goEasy.im.removePrivateConversation({
					userId: conversation.userId,
					onSuccess: function() {
						uni.hideLoading();
					},
					onFailed: function(error) {
						uni.hideLoading();
						uni.showToast({
							title: failedDescription,
							icon: 'none'
						});
						console.log(error);
					}
				});
			} else {
				this.goEasy.im.removeGroupConversation({
					groupId: conversation.groupId,
					onSuccess: function() {
						uni.hideLoading()
					},
					onFailed: function(error) {
						uni.hideLoading();
						uni.showToast({
							title: failedDescription,
							icon: 'none'
						});
						console.log(error);
					}
				});
			}
		},
		renderConversations(content) {
			this.conversations = content.conversations;
			let unreadTotal = content.unreadTotal;
			this.setUnreadAmount(unreadTotal);
		},
		setUnreadAmount(unreadTotal) {
			this.unreadTotal = unreadTotal;
			if (this.unreadTotal > 0) {
				uni.setTabBarBadge({
					index: 0,
					text: this.unreadTotal.toString()
				});
			} else {
				uni.removeTabBarBadge({
					index: 0
				});
			}
		},
		navigateToChat(conversation) {
			let path = conversation.type === this.GoEasy.IM_SCENE.PRIVATE ?
				'/pages/30messageSub/privateChat/privateChat?to=' + conversation.userId :
				'/pages/30messageSub/groupChat/groupChat?to=' + conversation.groupId;
			uni.navigateTo({
				url: path
			});
		},
		showAction(conversation) {
			this.actionPopup.conversation = conversation;
			this.actionPopup.visible = true;
		}
	},
	// 职责:不要set的data 统一用computed实现(能用computed实现的尽量用他实现 不要用data和method处理) 命名规范：前缀加calc 有返回值的不需要传参的method用computed实现 
	computed: {
		// 查询条件变化用于监控 命名方式以 calc加data的接口in
		//calcGetStudentListIn() {
		//    return this.$_.cloneDeep(this.getStudentListIn);
		//},

		// 接口返回值处理 calc加data的接口out 命名规范：前缀加calc
		//calcGetStudentListOut() {
		//    let dataList = this.$_.cloneDeep(this.getStudentListOut.dataList);
		//    dataList.forEach((item, index) => {
		//        // 有初始化选中的Id 那么选中
		//        if (this.selctId == item.id) {
		//            this.$set(item, 'selected', true);
		//        } else {
		//            // 设置属性需要通过这种方式设置 如之前没有绑定这个属性 需要这种方式设置 不然没办法双向绑定  其他设置为false
		//            this.$set(item, 'selected', false);
		//        }
		//    });
		//    // 尽量用lodash链式语法进行数据处理
		//    const page = 1; // 第几页
		//    const limit = 5; // 每页多少条
		//    const dealList = this.$_(dataList).chain()
		//        .drop((page - 1) * limit) // 跳过前面数据
		//        .take(limit) // 取几个
		//        .filter(x => x.age <= 10) // 过滤
		//        .map(x => ({
		//            stuName: x.stuName,
		//            age: x.age
		//        })) // 映射数据
		//        .orderBy(['stuName', 'age'], ['desc', 'asc']) // 排序
		//        .uniqBy('stuName') // 去重
		//        .value();
		//    return dealList;
		//},
	},
	// 职责:格式化数据 有返回值的需要传参的method 用filters实现
	filters: {
		// 多个参数filter 调用  {{day|weekDayFmt(getStudentListIn.month)}} filter  命名规范：filter后缀加上Fmt
		//weekDayFmt(day, yearMonth) {
		//    var weekDay = moment(yearMonth + "-" + day).day();
		//    var weekObj = { 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 0: "日" };
		//    return weekObj[weekDay];
		//},
	},
	// 职责:数据变化后需要和接口交互
	watch: {
		// 监控查询条件的变化 自动请求数据
		//'calcGetStudentListIn': {
		//    handler(val, oldval) {
		//        if (this.$util.isChgForWatch(val, oldval, ['pageIndex', 'sarchValue'])) { // 监控对象中那些数据发生了变化
		//            this.getPageList();
		//        }
		//    },
		//    deep: true,
		//    immediate: true,
		//}
	}
};
